package com.loveto.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loveto.common.ImageDownloader;
import com.loveto.common.JsonUtils;
import com.loveto.constant.LovetoConstant;
import com.loveto.constant.LovetoGiftAnims;
import com.loveto.model.GiftInfo;

public class SelectWinnerCompleteActivity extends BaseActivity implements
View.OnClickListener{
	
	private String tournamentID;
	private LovetoGiftAnims giftAnims;
	private List<AnimationDrawable> giftAnimList;
	private List<GiftInfo> giftInfoList = new ArrayList<GiftInfo>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_select_winner_complete);
		
		//init
		giftAnims = new LovetoGiftAnims();
		giftAnimList = new ArrayList<AnimationDrawable>();
		
		// btn
		RelativeLayout btnFinalWinner = (RelativeLayout) findViewById(R.id.btn_final_winner);
		btnFinalWinner.setOnClickListener(this);
		
		// getIntent
		Intent intent = getIntent();
		tournamentID = intent.getStringExtra("tournamentID");
		String winnerMemberId = intent.getStringExtra("memberid");
		//String gender = intent.getStringExtra("gender");
		String age = intent.getStringExtra("age");
		String job = intent.getStringExtra("job");
		String height = intent.getStringExtra("height");
		Integer giftid = intent.getIntExtra("giftid", 0);
		List<Integer> giftidList = intent.getIntegerArrayListExtra("giftidList");
		
		// 우승자 셋팅
		TextView textView = (TextView) findViewById(R.id.winner_id1); 
		textView.setText(winnerMemberId+" 님이 우승하셨습니다!");
		textView = (TextView) findViewById(R.id.winner_id2); 
		textView.setText(winnerMemberId);
		textView = (TextView) findViewById(R.id.winner_age); 
		textView.setText("나이: "+age);
		textView = (TextView) findViewById(R.id.winner_height); 
		textView.setText("키: "+height);
		textView = (TextView) findViewById(R.id.winner_job); 
		textView.setText("직업: "+job);
		
		ImageDownloader imageDownloader = new ImageDownloader();// 사진 다운로드
		ImageView imgView = (ImageView) findViewById(R.id.winner_photo);
		imageDownloader.download(LovetoConstant.PHOTO_URL+winnerMemberId+"_1.jpg", imgView);
		
		// 방장 셋팅
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		String memberid = "";
		if(pref.contains("memberid")) {
			memberid = pref.getString("memberid", null);
			imgView = (ImageView) findViewById(R.id.user_photo);
			String imageUrl = LovetoConstant.PHOTO_THUMB_URL+memberid+".jpg";
			imageDownloader.download(imageUrl, imgView);
		}
		
		// 선물 셋팅
		imgView = (ImageView) findViewById(R.id.gift_imageview);
		
		if(giftid == 0) {
			//선물이 없으니 invisible
			LinearLayout gift_layout = (LinearLayout)findViewById(R.id.gift_layout);
			gift_layout.setVisibility(View.INVISIBLE);
		} else if (giftAnims.getGiftAnimMap().containsKey(giftid)) { 
			//로컬에 선물 아이디에 대한 애니메이션 리소스가 있으면
			imgView.setBackgroundResource(giftAnims.getGiftAnimMap().get(giftid)); //애니메이션 지정
			giftAnimList.add((AnimationDrawable)imgView.getBackground()); //애니메이션 배열에 추가 (나중에 한번에 start 하기 위해)
		} else {
			//현재 버전에 선물에 대한 애니메이션 리소스가 없으면 FTP의 1장짜리 이미지로 대체함
			StringBuffer sb = new StringBuffer();
			sb.append(LovetoConstant.GIFT_IMAGE_URL);
			sb.append(giftid);
			sb.append(".png");
			imageDownloader.download(sb.toString(), imgView);
		}
		
		// 방장에게 선물넣기  // 방장에게 능력치 추가
		if(isNetworkAvailableAndNotice()) {
			insertGiftAndAbilityToMaker(memberid, giftid, giftidList);
		}
	}
	
	private void insertGiftAndAbilityToMaker(final String memberid, final int giftid, final List<Integer> giftidList) {
		final Handler myHandler = new Handler();
		final ProgressDialog progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("우승자 선물과 참여자들의 선물 능력치가 반영되고 있습니다.");
		progressDialog.show();
		
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				myHandler.post(new Runnable() {
					@Override
					public void run() {
						try {
							// giftInfo 셋팅
							getGiftInfo();
							
							// 능력치 셋팅
							Map<String, Integer> map = new HashMap<String, Integer>();
							map.put("innocent", 0);
							map.put("cuty", 0);
							map.put("sexy", 0);
							map.put("intelligent", 0);
							for(Integer giftid : giftidList) {
								if(giftid > 0) {
									String category = giftInfoList.get(giftid - 1).getCategory();
									int ability = giftInfoList.get(giftid - 1).getAbility();
									ability += map.get(category);
									map.put(category, ability);
								}
							}
							
							// 화면 출력
							StringBuffer sb = new StringBuffer();
							TextView ability_textview = (TextView) findViewById(R.id.ability_textview); 
							sb.setLength(0); //섹시+3/청순+15/큐티+12/지적+7
							sb.append("섹시+"); sb.append(map.get("sexy")); sb.append("/");
							sb.append("청순+"); sb.append(map.get("innocent")); sb.append("/");
							sb.append("큐티+"); sb.append(map.get("cuty")); sb.append("/");
							sb.append("지적+"); sb.append(map.get("intelligent"));
							ability_textview.setText(sb.toString());

							// URL 제조
							sb.setLength(0);
							sb.append(LovetoConstant.INSERT_GIFT_ABILITY_TO_MAKER);
							sb.append("?memberid=");
							sb.append(memberid);
							sb.append("&tournamentID=");
							sb.append(tournamentID);
							if(giftid != 0) {
								sb.append("&mygiftid=");
								sb.append(giftid);
							}
							sb.append("&intelligent=");
							sb.append(map.get("intelligent"));
							sb.append("&sexy=");
							sb.append(map.get("sexy"));
							sb.append("&cuty=");
							sb.append(map.get("cuty"));
							sb.append("&innocent=");
							sb.append(map.get("innocent"));
							
							// 쿼리 실행
							/*JSONObject jsonObject = JsonUtils.getJSONfromURL(sb.toString());
							String result = jsonObject.get("result").toString();
							Log.d("tag", "result:" + result);*/
							String result = JsonUtils.getStringFromUrl(sb.toString());
							Log.d("tag", "result:" + result);
							
							// 결과에 따라~
							if("T".equals(result)) {
								viewToast("우승자 선물과 참여자들의 선물 능력치가 반영되었습니다");
							} else if("C".equals(result)){
								viewToast("우승자 선물과 참여자들의 선물 능력치가 반영되었습니다");
								viewToast("질문종료 후 3시간이내에 선택하셨으므로 클로버 5개를 지급해드립니다.");
							} else {
								viewToast("우승자 선물과 참여자들의 선물 능력치가 반영이 실패하였습니다.");
							}
							
						} catch(Exception e) {
							Log.d("tag", e.toString());
						} finally {
							progressDialog.dismiss();
						}
					}
				});
			}
		};
		new Thread(runnable).start();
	}
	
	private void getGiftInfo() {
		try {
			String jsonText = JsonUtils.getStringFromUrl(LovetoConstant.GIFT_LIST);
			//Log.d("tag", "jsonText : " + jsonText);
			JSONArray jsonArray = new JSONArray(jsonText);
			for (int i = 0; i < jsonArray.length();i++) {
				JSONObject object = jsonArray.getJSONObject(i);
				GiftInfo giftInfo = new GiftInfo(object.getInt("giftid"), object.getString("category"), object.getString("category_kor"), object.getString("size"), object.getString("name"), object.getInt("price"), object.getInt("ability"), object.getString("regdate"));
				giftInfoList.add(giftInfo);
			}
		}catch (JSONException e) {
			e.printStackTrace();
			Log.d("tag", "getGiftInfo() error, " + e.getMessage());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			Log.d("tag", "getGiftInfo() error, " + e.getMessage());
		} finally {
		}
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_final_winner:
			// 네트워크 이용못하면 빠져나감
			if(!isNetworkAvailableAndNotice())
				break;
			
			// URL
			StringBuffer sb = new StringBuffer();
			sb.append(LovetoConstant.SELECT_WINNER_ROUND_COMPLETE);
			sb.append("?tournamentid=");
			sb.append(tournamentID);
			sb.append("&message=");
			
			
			// 메시지 담겨있는 EditText
			EditText editText = (EditText) findViewById(R.id.message);
			// 메시지 서버로 전달
			try {
				String message = URLEncoder.encode(editText.getText().toString(), "UTF-8");
				sb.append(message);
				
				JSONObject jsonObject = JsonUtils.getJSONfromURL(sb.toString());
				try {
					if("F".equals(jsonObject.get("result").toString())) {
						viewToast("메시지 전송이 잘 되지 않았습니다.");
					} else {
						Intent intent = new Intent(SelectWinnerCompleteActivity.this, JoinedTournamentListActivity.class);
						startActivity(intent);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			// // // 메시지 서버로 전달완료
			
			break;
		}
	}
	
	@Override
	public void onBackPressed() {
		new AlertDialog.Builder(SelectWinnerCompleteActivity.this)
		.setTitle("알림")
		.setMessage("초기 페이지로 갑니다. 가시겠습니까?")
		.setPositiveButton("예", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
		        // TODO Auto-generated method stub
				Intent intent = new Intent(SelectWinnerCompleteActivity.this, InfoTournamentActivity.class);
		  		intent.putExtra("tournamentID", tournamentID);
		  		startActivity(intent);
		        finish();
			}
			
		})
		.setNegativeButton("아니요", null)
		.show();
	}
	
}
